//
//  HMPullDownRefresh.swift
//  sinaweibo
//
//  Created by WGP on 16/4/15.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit

//刷新控件的高度
private let HMPullDownRefreshHeight: CGFloat = 60

enum HMPullDownRefreshViewStatus: Int
{
    case Normal       //箭头朝下
    case PullToRefresh
    case Refreshing
}

class HMPullDownRefresh: UIView {

    //    MARK: - 属性
    private var superScrollView: UIScrollView?
    
    var pullDownRefreshHandle: (()->())?
    
    private var currentStatus: HMPullDownRefreshViewStatus = .Normal
    {
        didSet
        {
//            当状态切换了,根据不同状态设置不同的内容
            switch currentStatus
            {
                
            case .Normal:
                circleView.hidden = true
                arrowView.hidden = false
                messageLabel.text = "下拉刷新"
                
                UIView.animateWithDuration(HMDefaultAnimationDuration, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformIdentity
                })
                
            case .PullToRefresh:
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(HMDefaultAnimationDuration, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                messageLabel.text = "正在刷新"
                
                circleView.hidden = false
                arrowView.hidden = true
                
//                添加动画
                let animataion = CABasicAnimation(keyPath: "transform.rotation")
                animataion.toValue = M_PI*2
                animataion.repeatCount = MAXFLOAT
                animataion.duration = 0.5
                animataion.removedOnCompletion = false
                
//                防止动画叠加,增加一个key后,每次动画就会覆盖前面一个动画,覆盖
                circleView.layer.addAnimation(animataion, forKey: "animation")
                
//                让tableView往下走走刷新控件的高度,不然刷新控件会被挡住
                
                UIView.animateWithDuration(HMDefaultAnimationDuration, animations: { () -> Void in
                    self.superScrollView!.contentInset.top += HMPullDownRefreshHeight
                })
                
//                通知控制器开始刷新
                pullDownRefreshHandle?()
            }
        }
    }
    
//    MARK: - 构造方法
    override init(frame: CGRect) {
        
        let newFrame = CGRect(x: 0, y: -HMPullDownRefreshHeight, width: UIScreen.mainScreen().bounds.width, height: HMPullDownRefreshHeight)
        super.init(frame: newFrame)
        
//        backgroundColor = UIColor.brownColor()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI()
    {
//        1.添加子控件
        addSubview(circleView)
        addSubview(arrowView)
        addSubview(messageLabel)
        
        circleView.hidden = true
        
//        2.添加约束
        circleView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        
        arrowView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.circleView)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.left.equalTo(circleView.snp_right).offset(10)
        }
    }
    
    
    ///重写willMoveToSuperview方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
//        判断父控件是否UIScreenView或其子类
        if let scrollView = newSuperview as? UIScrollView
        {
            superScrollView = scrollView
            
//            使用KVO监听scrollView的滚动
//            要监听谁的属性,就用谁来调用
            
            superScrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        }
    }
    
//    KVO记得要移除,相当于OC中的dedalloc方法
    deinit
    {
        removeObserver(self, forKeyPath: "contentOffset")
    }
    
//    实现KVo监听方法,方法是固定的
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if superScrollView!.dragging
        {
            if currentStatus == .Normal && superScrollView!.contentOffset.y < -(superScrollView!.contentInset.top + HMPullDownRefreshHeight)
            {
                currentStatus = .PullToRefresh
            }
            else if currentStatus == .PullToRefresh && superScrollView!.contentOffset.y > -(superScrollView!.contentInset.top + HMPullDownRefreshHeight)
            {
                currentStatus = .Normal
            }
        }
        else if currentStatus == .PullToRefresh
        {
            currentStatus = .Refreshing
        }
        
    }
    
//    MARK: - 开始和结束刷新
    func startRefreshing()
    {
        currentStatus = .Refreshing
    }
    
    func endRefreshing()
    {
        currentStatus = .Normal
        
        UIView.animateWithDuration(HMDefaultAnimationDuration) { () -> Void in
            
            self.superScrollView!.contentInset.top -= HMPullDownRefreshHeight
        }
    }
    
//    MARK: - 懒加载控件
    private lazy var arrowView: UIImageView = UIImageView(imageName: "tableview_pull_refresh");
    private lazy var circleView: UIImageView = UIImageView(imageName: "tableview_loading")
    
    private lazy var messageLabel: UILabel =
    {
        let label = UILabel(fontSize: 14, textColor: UIColor.darkGrayColor())
        
        label.text = "下拉刷新"
        
        return label
    }()
    
}










